<template>
  <div class="projectContainer">
    <!-- 头部 -->
    <div class="header">
      <div class="title" title="创建项目">Create</div>
    </div>

    <div class="divide"></div>

    <!-- 创建项目 -->
    <CreateProject :changeRefreshSignal="changeRefreshSignal" />

    <div class="divide"></div>

    <div class="header">
      <div class="title" title="项目列表">Projects</div>
    </div>

    <div class="divide"></div>

    <!-- 项目列表 -->
    <ProjectList
      :page="page"
      :pageSize="size"
      :setTotal="setTotal"
      :refreshSignal="refreshSignal"
      :changeRefreshSignal="changeRefreshSignal"
    />

    <!-- 分页栏 -->
    <PaginationBar
      :size="size"
      :page="page"
      :total="total"
      :sizeChange="sizeChange"
      :currentChange="pageChange"
    />
    <div class="divide"></div>
  </div>
</template>

<script lang="tsx" setup>
import { defineComponent, onMounted, ref, watch } from 'vue'
import { useThemeStore, useProjectStore } from '@/features/store/store'
import { storeToRefs } from 'pinia'
import {
  Sort,
  DeleteFilled,
  Setting,
  Tools,
  Clock,
  Plus,
  InfoFilled,
  CircleCloseFilled,
  StarFilled,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import styles from './project.module.less'
import {
  createProjectApi,
  getProjectPageListAPi,
  deleteProjectApi,
  updatreProjectApi,
} from '@/request/api/project'
import { getHarvestPageListApi } from '@/request/api/harvest'
import {
  createModulesApi,
  getProjectModulesApi,
  deleteModuleApi,
  updateModuleApi,
} from '@/request/api/module'
import LoadingClass from '@/utils/utilClass/Loading'
import PaginationBar from '@/components/PaginationBar.vue'

// 是否更新数据信号
const refreshSignal = ref<string>('')
// 更新信号
const changeRefreshSignal = () => (refreshSignal.value = new Date() + '')

//
// 创建项目
const CreateProject = defineComponent({
  props: {
    changeRefreshSignal: { type: Function, defaule: '' },
  },
  setup(props) {
    const { buttonColor } = storeToRefs(useThemeStore())

    // 创建项目
    const createHeight = ref<'105px' | '28px'>('28px')
    const createOverflow = ref<'hidden' | ''>('hidden')
    const extendCreateBar = ref<true | false>(false)
    // 切换创建栏
    const toggleCreate = (): void => {
      if (extendCreateBar.value) {
        extendCreateBar.value = false
        createHeight.value = '28px'
        createOverflow.value = 'hidden'
      } else {
        createHeight.value = '105px'
        createOverflow.value = ''
        setTimeout(() => (extendCreateBar.value = true), 180)
      }
    }

    const title = ref<string>('')
    const description = ref<string>('')
    const ClassLoading = new LoadingClass()

    // 创建新项目
    const createProject = async (): Promise<void> => {
      if (!title.value || !description.value)
        return ClassLoading.setTips('请将参数补充完整！')

      const data = {
        title: title.value,
        description: description.value,
      }
      ClassLoading.loading.value = true
      const res = await createProjectApi(data)
      ClassLoading.loading.value = false

      if (res.code !== 200) return ClassLoading.setTips('创建新项目失败！')
      ClassLoading.setTips('创建新项目成功！')
      title.value = ''
      description.value = ''
      useProjectStore().resetProjectList()
      props.changeRefreshSignal()
    }

    return () => (
      <div
        class={styles.createProject}
        style={{ height: createHeight.value, overflow: createOverflow.value }}
      >
        <div class={styles.tipsTxt} v-show={!extendCreateBar.value}>
          创建新项目
        </div>

        <div class={styles.detailInfo} v-show={extendCreateBar.value}>
          <div class={styles.p_title}>
            <div class={styles.label}>
              <el-icon size="12" color="red" title="必填项">
                <StarFilled />
              </el-icon>
              项目名称：
            </div>
            <div>
              <el-input
                v-model={title.value}
                placeholder="Please input project title"
                clearable
                maxlength="16"
                show-word-limit
              />
            </div>
            <div>
              <el-button
                type="primary"
                plain
                color={buttonColor.value}
                loading={ClassLoading.loading.value}
                onClick={createProject}
              >
                创建
              </el-button>

              <div class={styles.tips}>{ClassLoading.resultTips.value}</div>
            </div>
          </div>

          <div class={styles.p_description}>
            <div class={styles.label}>项目描述：</div>
            <div>
              <el-input
                v-model={description.value}
                placeholder="Please input project description"
                type="textarea"
                maxlength="60"
                show-word-limit
              />
            </div>
          </div>
        </div>

        <div class={styles.toggle}>
          <div onClick={toggleCreate}>
            <el-icon size="24" color={buttonColor.value}>
              <Sort />
            </el-icon>
          </div>
        </div>
      </div>
    )
  },
})

// 分页栏相关信息
const size = ref<number>(12)
const page = ref<number>(1)
const total = ref<number>(0)
const pageChange = (p: number) => {
  page.value = p
  changeRefreshSignal()
}
const sizeChange = (s: number) => {
  size.value = s
  changeRefreshSignal()
}
const setTotal = (t: number) => (total.value = t)

//
// 项目列表
const ProjectList = defineComponent({
  props: {
    page: { type: Number, defaule: '' },
    pageSize: { type: Number, defaule: '' },
    setTotal: { type: Function, defaule: '' },
    refreshSignal: { type: String, defaule: '' },
    changeRefreshSignal: { type: Function, defaule: '' },
  },
  setup(props) {
    onMounted(() => {
      getProjectPageList()
    })
    // 监听更新信号，更新列表
    watch(
      () => props.refreshSignal,
      () => getProjectPageList()
    )

    // 项目列表
    const projectList = ref<getProjectResultItf[]>(null)
    // 分页获取项目列表
    const getProjectPageList = async () => {
      const res = await getProjectPageListAPi({
        page: props.page,
        pageSize: props.pageSize,
      })

      if (res.code !== 200) return (projectList.value = [])
      props.setTotal(res.data.total)
      projectList.value = res.data.records
    }

    // 当前正在操作的卡片id
    const settingCardId = ref<string>('')
    const setSettingCardId = (id: string) => (settingCardId.value = id)

    // 项目信息展示
    const ProjectInfo = defineComponent({
      props: {
        id: { type: String, default: '' },
        title: { type: String, default: '' },
        createTime: { type: String, default: '' },
        description: { type: String, default: '' },
        currentId: { type: String, default: '' },
        setCurrentId: { type: Function, default: '' },
        changeRefreshSignal: { type: Function, defaule: '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())

        //
        // 删除项目
        const deleteProject = async () => {
          const res = await deleteProjectApi(props.id)
          if (res.code !== 200) return ElMessage.error('删除失败！')
          useProjectStore().resetProjectList()
          props.changeRefreshSignal()
        }

        return () => (
          <div class={styles.projectInfo}>
            <div class={styles.info}>
              <div class={styles.title}>
                <el-icon
                  size="22"
                  color={buttonColor.value}
                  title={'创建时间：' + props.createTime}
                >
                  <Clock />
                </el-icon>
                &nbsp;{props.title}
              </div>

              <div class={styles.setting}>
                <div v-show={props.id !== props.currentId}>
                  <el-popconfirm
                    confirm-button-text="确认"
                    cancel-button-text="取消"
                    title="确定删除吗？"
                    onConfirm={deleteProject}
                    v-slots={{
                      reference: () => (
                        <el-icon
                          size="24"
                          color={buttonColor.value}
                          title="删除好友"
                        >
                          <DeleteFilled />
                        </el-icon>
                      ),
                    }}
                  ></el-popconfirm>
                </div>
                <div v-show={props.id !== props.currentId}>
                  <el-icon
                    size="24"
                    color={buttonColor.value}
                    onClick={() => props.setCurrentId(props.id)}
                    title="设置"
                  >
                    <Setting />
                  </el-icon>
                </div>
                <div v-show={props.id === props.currentId}>
                  <el-icon
                    size="24"
                    color={buttonColor.value}
                    onClick={() => props.setCurrentId('')}
                    title="设置"
                  >
                    <Tools />
                  </el-icon>
                </div>
              </div>
            </div>
            <div class={styles.description} title={props.description}>
              {props.description}
            </div>
          </div>
        )
      },
    })

    // 更新项目信息
    const UpdateProjectInfo = defineComponent({
      props: {
        title: { type: String, default: '' },
        projectId: { type: String, default: '' },
        description: { type: String, default: '' },
        changeRefreshSignal: { type: Function, default: '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())

        const toggle = ref<boolean>(false)
        const setToggleExtend = () => (toggle.value = true)
        const setToggleHidden = () => (toggle.value = false)

        const title = ref<string>(props.title)
        const description = ref<string>(props.description)
        const ClassLoading = new LoadingClass()

        // 更新信息
        const updatreProject = async () => {
          ClassLoading.loading.value = true
          const res = await updatreProjectApi({
            id: props.projectId,
            title: title.value,
            description: description.value,
          })
          ClassLoading.loading.value = false

          if (res.code !== 200) return ClassLoading.setTips('更新信息失败！')
          ClassLoading.setTips('更新项目信息成功！')
          props.changeRefreshSignal()
        }

        return () => (
          <div class={styles.updateProjectInfo}>
            {/* 展开创建模块 */}
            <div class={styles.label}>
              <div>更新信息</div>

              <el-button
                v-show={toggle.value}
                plain
                size="small"
                color={buttonColor.value}
                onClick={setToggleHidden}
              >
                收起
              </el-button>
              <el-button
                v-show={!toggle.value}
                plain
                size="small"
                color={buttonColor.value}
                onClick={setToggleExtend}
              >
                更新信息
              </el-button>
            </div>

            {/* 输入框 */}
            <div class={styles.projectInfo} v-show={toggle.value}>
              <div class={styles.title}>
                <div class={styles.label}>
                  <el-icon size="12" color="red" title="必填项">
                    <StarFilled />
                  </el-icon>
                  项目名称：
                </div>
                <div>
                  <el-input
                    v-model={title.value}
                    size="small"
                    placeholder="Please input project title"
                    clearable
                    maxlength="16"
                    show-word-limit
                  />
                </div>
                <div>
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    color={buttonColor.value}
                    loading={ClassLoading.loading.value}
                    onClick={updatreProject}
                  >
                    更新
                  </el-button>

                  <div class={styles.tips}>{ClassLoading.resultTips.value}</div>
                </div>
              </div>

              <div class={styles.description}>
                <div class={styles.label}>项目描述：</div>
                <div>
                  <el-input
                    v-model={description.value}
                    placeholder="Please input project description"
                    type="textarea"
                    size="small"
                    maxlength="60"
                    show-word-limit
                  />
                </div>
              </div>
            </div>
          </div>
        )
      },
    })

    // 批量创建模块
    const CreateModules = defineComponent({
      props: {
        projectId: { type: String, default: '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())

        const toggle = ref<boolean>(false)
        const setToggleExtend = () => {
          toggle.value = true
          createModulesList.value = [{ name: '', description: '' }]
        }
        const setToggleHidden = () => {
          createModulesList.value = []
          toggle.value = false
        }

        // 要创建的模块列表
        const createModulesList = ref<createModuleItf[]>([])
        // 添加模块项
        const addModule = () => {
          createModulesList.value = [
            ...createModulesList.value,
            { name: '', description: '' },
          ]
        }

        const ClassLoading = new LoadingClass()

        // 批量创建模块
        const createModules = async () => {
          const list: createModuleItf[] = createModulesList.value.filter(
            (item) => item.name !== '' && item.name !== null
          )

          if (list.length === 0) return ClassLoading.setTips('模块名不能为空！')

          ClassLoading.loading.value = true
          const res = await createModulesApi({
            projectId: props.projectId,
            list,
          })
          ClassLoading.loading.value = false

          if (res.code !== 200) return ClassLoading.setTips('创建失败！')
          ClassLoading.setTips('创建成功！')
          createModulesList.value = [{ name: '', description: '' }]
        }

        return () => (
          <div class={styles.createModules}>
            {/* 展开创建模块 */}
            <div class={styles.label} v-show={!toggle.value}>
              <div>创建模块</div>
              <el-button
                plain
                size="small"
                color={buttonColor.value}
                onClick={setToggleExtend}
              >
                创建
              </el-button>
            </div>

            {/* 收起创建模块，以及添加新的模块 */}
            <div class={styles.label} v-show={toggle.value}>
              <div>
                批量创建模块 &nbsp;
                <el-button
                  circle
                  plain
                  color={buttonColor.value}
                  size="small"
                  onClick={addModule}
                  v-slots={{
                    icon: () => (
                      <el-icon title="添加">
                        <Plus />
                      </el-icon>
                    ),
                  }}
                />
              </div>

              <div>
                <div class={styles.tips}>{ClassLoading.resultTips.value}</div>
                <el-button
                  plain
                  color={buttonColor.value}
                  size="small"
                  loading={ClassLoading.loading.value}
                  onClick={createModules}
                >
                  创建
                </el-button>
                <el-button
                  plain
                  size="small"
                  color={buttonColor.value}
                  onClick={setToggleHidden}
                >
                  收起
                </el-button>
              </div>
            </div>

            {/* 循环遍历出要添加的模块项 */}
            {createModulesList.value.map((item) => {
              return (
                <div class={styles.moduleItem}>
                  <div class={styles.modele_label}>
                    <el-icon size="12" color="red" title="必填项">
                      <StarFilled />
                    </el-icon>
                    模块名：
                  </div>
                  <div class={styles.module_input1}>
                    <el-input
                      v-model={item.name}
                      size="small"
                      maxlength={10}
                      show-word-limit
                      placeholder="module name"
                    />
                  </div>

                  <div class={styles.modele_label}>模块描述：</div>
                  <div class={styles.module_input2}>
                    <el-input
                      v-model={item.description}
                      size="small"
                      maxlength={30}
                      show-word-limit
                      placeholder="module description"
                    />
                  </div>
                </div>
              )
            })}
          </div>
        )
      },
    })

    // 模块列表
    const ModuleList = defineComponent({
      props: {
        projectId: { type: String, default: '' },
        settingCardId: { type: String, default: '' },
      },
      setup(props) {
        const { buttonColor } = storeToRefs(useThemeStore())

        watch(
          () => props.settingCardId,
          () => {
            if (props.projectId === props.settingCardId) getProjectModules()
          }
        )

        // 切换展开列表和显示模块列表
        const showList = ref<boolean>(true)
        const setShowList = () => {
          showList.value = !showList.value
          if (showList.value) getProjectModules()
          // 隐藏修改模块功能
          resetModifyInfo()
          // 隐藏删除模块功能
          showDelete.value = false
        }

        // 模块列表
        const moduleList = ref<getProjectModulesResItf[]>([])
        // 获取项目模块列表
        const getProjectModules = async () => {
          const res = await getProjectModulesApi(props.projectId)
          if (res.code !== 200) return (moduleList.value = [])
          moduleList.value = res.data
        }

        // 切换删除和展示模块
        const showDelete = ref<boolean>(false)
        const setShowDelete = () => {
          showDelete.value = !showDelete.value
          // const el = document.getElementById('toggleDelete')
          // setTimeout(() => el.blur(), 400)
          // 开启删除功能时，禁止修改模块功能
          resetModifyInfo()
        }

        const ClassLoading = new LoadingClass()
        // 删除模块
        const deleteModule = async (id: string) => {
          const res = await deleteModuleApi(id)
          if (res.code !== 200) return ClassLoading.setTips('删除此模块失败！')
          ClassLoading.setTips('删除此模块成功！')
          getProjectModules()
        }

        // 修改模块
        const moduleName = ref<string>('')
        const moduleDesc = ref<string>('')
        const moduleId = ref<string>('')
        // 设置模块的修改信息，并开启修改功能
        const setModuleInfo = (name: string, desc: string, id: string) => {
          moduleName.value = name
          moduleDesc.value = desc
          moduleId.value = id
        }
        // 重置信息
        const resetModifyInfo = () => {
          moduleId.value = ''
          moduleName.value = ''
          moduleDesc.value = ''
        }

        const ClassLoading2 = new LoadingClass()
        // 修改模块
        const updateModule = async () => {
          if (!moduleName.value) return ClassLoading2.setTips('模块名不能为空')
          const data = {
            projectId: props.projectId,
            id: moduleId.value,
            name: moduleName.value,
            description: moduleDesc.value,
          }
          ClassLoading2.loading.value = true
          const res = await updateModuleApi(data)
          ClassLoading2.loading.value = false

          if (res.code !== 200) return ClassLoading2.setTips('修改失败！')
          ClassLoading2.setTips('修改模块信息成功！')
          resetModifyInfo()
          getProjectModules()
        }

        return () => (
          <div class={styles.moduleList}>
            {/* 标题项 */}
            <div class={styles.label}>
              <div>模块列表: &nbsp; {ClassLoading2.resultTips.value}</div>

              <div>
                <div class={styles.tips}>{ClassLoading.resultTips.value}</div>
                <el-button
                  v-show={showList.value}
                  plain
                  size="small"
                  color={buttonColor.value}
                  onClick={setShowDelete}
                >
                  {showDelete.value ? '完成' : '删除'}
                </el-button>

                <el-button
                  id="toggleShow"
                  plain
                  size="small"
                  color={buttonColor.value}
                  onClick={setShowList}
                >
                  {showList.value ? '收起' : '展开'}
                </el-button>
              </div>
            </div>

            {/* 修改模块 */}
            <div class={styles.modifyModule} v-show={moduleId.value !== ''}>
              <div class={styles.modele_btns}>
                <el-button
                  plain
                  size="small"
                  color={buttonColor.value}
                  loading={ClassLoading2.loading.value}
                  onClick={resetModifyInfo}
                >
                  取消
                </el-button>
                <el-button
                  plain
                  size="small"
                  color={buttonColor.value}
                  loading={ClassLoading2.loading.value}
                  onClick={updateModule}
                >
                  修改
                </el-button>
              </div>

              <div class={styles.modele_label}>
                <el-icon size="12" color="red" title="必填项">
                  <StarFilled />
                </el-icon>
                模块名：
              </div>
              <div class={styles.module_input1}>
                <el-input
                  v-model={moduleName.value}
                  size="small"
                  maxlength={10}
                  show-word-limit
                  placeholder="module name"
                />
              </div>
              <div class={styles.modele_label}>模块描述：</div>
              <div class={styles.module_input2}>
                <el-input
                  v-model={moduleDesc.value}
                  size="small"
                  maxlength={30}
                  show-word-limit
                  placeholder="module description"
                />
              </div>
            </div>
            <div class={styles.divide} v-show={moduleId.value !== ''}></div>

            {/* 模块列表 */}
            <div class={styles.list} v-show={showList.value}>
              {moduleList.value.map((item) => {
                const mId = item.id
                return (
                  <div id={moduleId.value === mId ? styles.settingModule : ''}>
                    {item.name} &nbsp;
                    {showDelete.value ? (
                      <div>
                        <el-icon
                          size="18"
                          title={'(点击将直接删除此模块) ' + item.description}
                          onClick={() => deleteModule(item.id)}
                        >
                          <CircleCloseFilled />
                        </el-icon>
                      </div>
                    ) : (
                      <div>
                        <el-icon
                          size="18"
                          title={'(点击可修改模块信息) ' + item.description}
                          color={buttonColor.value}
                          onClick={() =>
                            setModuleInfo(item.name, item.description, item.id)
                          }
                        >
                          <InfoFilled />
                        </el-icon>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          </div>
        )
      },
    })

    // 收获列表
    const HarvestList = defineComponent({
      props: {
        projectId: { type: String, default: '' },
        settingCardId: { type: String, default: '' },
      },
      setup(props) {
        watch(
          () => props.settingCardId,
          () => {
            if (props.projectId === props.settingCardId) getHarvestPageList()
          }
        )

        // 收获列表
        const harvestList = ref<getHarvestResultItf[]>([])

        // 分页获取项目收获
        const getHarvestPageList = async () => {
          const res = await getHarvestPageListApi({
            projectId: props.projectId,
            page: 1,
            pageSize: 10,
          })

          if (res.code !== 200) return (harvestList.value = [])
          harvestList.value = res.data.records
        }

        return () => (
          <div class={styles.harvestList}>
            <div class={styles.label}>收获列表: </div>

            {harvestList.value.map((item) => {
              return (
                <div class={styles.list} key={item.id}>
                  {item.description}
                </div>
              )
            })}
          </div>
        )
      },
    })

    return () => (
      <div class={styles.projectList}>
        {projectList.value?.map((item) => {
          return (
            <div
              class={styles.card}
              key={item.id}
              id={settingCardId.value === item.id ? styles.settingCard : ''}
            >
              <ProjectInfo
                id={item.id}
                title={item.title}
                createTime={item.createTime}
                description={item.description}
                currentId={settingCardId.value}
                setCurrentId={setSettingCardId}
                changeRefreshSignal={props.changeRefreshSignal}
              />

              <div
                class={styles.divide}
                v-show={settingCardId.value === item.id}
              ></div>

              {/* 更新项目信息 */}
              <UpdateProjectInfo
                v-show={settingCardId.value === item.id}
                title={item.title}
                projectId={item.id}
                description={item.description}
                changeRefreshSignal={props.changeRefreshSignal}
              />

              <div
                class={styles.divide}
                v-show={settingCardId.value === item.id}
              ></div>

              {/* 批量创建模块 */}
              <CreateModules
                v-show={settingCardId.value === item.id}
                projectId={item.id}
              />

              <div
                class={styles.divide}
                v-show={settingCardId.value === item.id}
              ></div>

              {/* 模块列表 */}
              <ModuleList
                v-show={settingCardId.value === item.id}
                projectId={item.id}
                settingCardId={settingCardId.value}
              />

              <div
                class={styles.divide}
                v-show={settingCardId.value === item.id}
              ></div>

              {/* 收获列表模块 */}
              <HarvestList
                v-show={settingCardId.value === item.id}
                projectId={item.id}
                settingCardId={settingCardId.value}
              />
            </div>
          )
        })}
      </div>
    )
  },
})
</script>

<style lang="less" scoped>
@fontstyle: comic Sans MS, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
  Oxygen, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;

.projectContainer {
  width: calc(100% - 24px);
  min-height: 100%;
  padding: 12px;

  > .header {
    width: 100%;
    transition: 0.2s;

    > .title {
      font-family: @fontstyle;
      font-size: 18px;
      font-weight: bold;
      color: var(--theme-active-label);
      user-select: none;
    }
  }

  > .divide {
    height: 2px;
    width: 100%;
    background-color: var(--theme-header);
    margin-top: 10px;
    margin-bottom: 10px;
  }
}
</style>
